import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mywindows/app_util.dart';
import 'package:excel/excel.dart';
import 'package:file_selector/file_selector.dart';
import 'package:xml/xml.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _filePath = '';
  String _fileName = '';
  String _BzBl = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('文件转换工具'),
      ),
      body: Column(
        children: <Widget>[
          // 输入内容区
          Container(
            height: AppUtil.textFieldHeight,
            margin: EdgeInsets.only(top: AppUtil.marginTop),
            child: Row(
              children: [
                Row(
                  children: [
                    Text('产品名称:'),
                    Container(
                      width: 500,
                      child: TextField(
                        decoration: InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)))),
                      ),
                    )
                  ],
                ),
                Row(
                  children: [
                    Text('公司名称:'),
                    Container(
                      width: 500,
                      child: TextField(
                        decoration: InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)))),
                      ),
                    )
                  ],
                ),
              ],
            ),
          ),
          // 第二行
          Container(
            margin: EdgeInsets.only(top: AppUtil.marginTop),
            child: Row(
              children: [
                Container(
                  height: AppUtil.textFieldHeight,
                  child: Row(
                    children: [
                      Text('批准文号:'),
                      Container(
                        width: 200,
                        child: TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)))),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: AppUtil.textFieldHeight,
                  child: Row(
                    children: [
                      Text('操作员（选填）:'),
                      Container(
                        width: 200,
                        child: TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)))),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: AppUtil.textFieldHeight,
                  child: Row(
                    children: [
                      Text('批号:'),
                      Container(
                        width: 200,
                        child: TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)))),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: AppUtil.textFieldHeight,
                  child: Row(
                    children: [
                      Text('规格:'),
                      Container(
                        width: 200,
                        child: TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)))),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          // 第三行
          Container(
            margin: EdgeInsets.only(top: AppUtil.marginTop),
            child: Row(
              children: [
                Container(
                  height: AppUtil.textFieldHeight,
                  child: Row(
                    children: [
                      Text('最小贴码单位:'),
                      Container(
                        width: 200,
                        child: TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)))),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: AppUtil.textFieldHeight,
                  child: Row(
                    children: [
                      Text('最小包装单位:'),
                      Container(
                        width: 200,
                        child: TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)))),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: AppUtil.textFieldHeight,
                  child: Row(
                    children: [
                      Text('最小单位比值（选填）:'),
                      Container(
                        width: 200,
                        child: TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)))),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),

          // 底部功能区按钮
          Container(
            height: 60,
            alignment: Alignment.bottomCenter,
            child: Row(
              children: [
                RaisedButton(
                  onPressed: () {
                    _openFile();
                  },
                  child: Text('导入文件'),
                ),
                RaisedButton(
                  onPressed: () {
                    _createXMLFile();
                  },
                  child: Text('生成文件'),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  /**
   * 创建日期：2022/3/29
   * @author Zhangzhenguo
   * @version 1.0
   * 类说明：打开文件
   */
  _openFile() async {
    final typeGroup = XTypeGroup(label: 'excel', extensions: ['xlsx', 'xls']);
    final file = await openFile(acceptedTypeGroups: [typeGroup]);
    if (file != null) {
      _filePath = file.path;
      _fileName = file.name;
      print("文件路径：" + _filePath);
      print("文件名称：" + _fileName);
      // 解析excel内容
      _getExcelContents(_filePath);
    }
  }

  /**
   * 创建日期：2022/3/29
   * @author Zhangzhenguo
   * @version 1.0
   * 类说明：读取excel文件内容
   */
  void _getExcelContents(String filePath) async {
    var bytes = File(filePath).readAsBytesSync();
    var excel = Excel.decodeBytes(bytes);
    List<List<dynamic>> datas = [];
    List<dynamic> data = [];
    for (var table in excel.tables.keys) {
      // print("sheetName："+table); //sheet Name
      // print(excel.tables[table]?.maxCols);
      // print(excel.tables[table]?.maxRows);
      for (var row in excel.tables[table]!.rows) {
        if (row[3] == null && row[4] == null) {
          if (datas.length > 0) {
            print(datas.length - 1);
            datas.removeAt(0);
            // print(datas);
            for (var item in datas) {
              print(item[3].toString().split('，')[1]);
            }

            var size = datas.length - 1;
            _BzBl = "1:" + String.fromCharCode(size);
            return;
          }
        } else {
          datas.add(row);
        }
      }
    }
  }

  /**
   * 生成xml文件
   */
  Future<void> _createXMLFile() async {
    final builder = XmlBuilder();
    builder.processing('xml', 'version="1.0" encoding="UTF-8"');
    builder.element('DataList', nest: () {
      builder.attribute('corpName', '韩国RNL');
      builder.attribute('manCode', '19060101');
      builder.attribute('dataType', 'wareHouseIn');
      builder.attribute('version', '1.0');
      builder.attribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
      builder.attribute('xsi:noNamespaceSchemaLocation', '兽药产品入库数据_生产企业.xsd');
      builder.element('Product', nest: () {
        builder.attribute('productName', '枸橼酸苹果酸粉');
        builder.attribute('pzwh', '（2017）外兽药证字20号');
        builder.attribute('packing', '500g');
        builder.attribute('batchNo', 'J001');
        builder.attribute('specification', '1000g:枸橼酸400g+DL-苹果酸100g');
        builder.attribute('minPackUnit', '瓶');
        builder.attribute('minTagUnit', '瓶');
        builder.attribute('tagPackRatio', '1');
        builder.attribute('tagRatio', '1:20');
        builder.attribute('produceDate', '2020-03-24');
        builder.attribute('operator', 'operator');
        builder.attribute('oprDate', '2020-03-25');
        builder.attribute('count', '0');
        builder.attribute('countUnit', '0');
        for(int i=0;i<20;i++){
          builder.element('Data', nest: (){
            builder.attribute('code', '202003200192800003350177');
          });
        }
      });
    });
    final document = builder.buildDocument();
    print(document.toXmlString(pretty: true, indent: "\t"));
    final String fileName = "hello.xml";
    final String? path = await FileSelectorPlatform.instance.getSavePath(
      // Operation was canceled by the user.
      suggestedName: fileName,
    );
    if (path == null) {
      return;
    }
    debugPrint('xml存储路径：$path');
    final fileData = Utf8Encoder().convert(document.toString());
    const String fileMimeType = 'text/xml';
    final XFile textFile = XFile.fromData(fileData, mimeType: fileMimeType, name: fileName);
    await textFile.saveTo(path);


    // final String text =document.toString();
    // final Uint8List fileData = Uint8List.fromList(text.codeUnits);
    //
    // await textFile.saveTo(path);
  }
}
